package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.mapper.SkuMapper;
import com.heima.pojo.dto.SkuDto;
import com.heima.pojo.domain.PageResult;
import com.heima.pojo.domain.Sku;
import com.heima.pojo.vo.PageQueryResponse;
import com.heima.service.SkuService;
import com.heima.utils.SnowflakeIdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class SkuServiceImpl implements SkuService {

    @Autowired
    private SkuMapper skuMapper;

    // 在 Service 中初始化（或通过Spring注入）
    private SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1); // 参数: 数据中心ID, 机器ID

    @Override
    public Boolean insertSku(SkuDto skuDto) {
        Sku sku = new Sku();
        BeanUtils.copyProperties(skuDto,sku);
        sku.setIsDiscount(false);
        sku.setCreateTime(LocalDateTime.now());
        sku.setUpdateTime(LocalDateTime.now());
        // 如果前端未传 sku_id，则自动生成
        if (sku.getSkuId() == null) {
         /*   Page<PageQueryResponse> list = skuMapper.selectList(null);

            boolean idExists = list.stream()
                    .map(PageQueryResponse::getSkuId)
                    .anyMatch(id -> id != null && id.equals(skuId));
            if (!idExists) {
                sku.setSkuId(skuId);
            }*/
            Long skuId =idGenerator.nextId(); // 生成ID
            sku.setSkuId(skuId); // 设置到实体对象
        }
        int res = skuMapper.insertSku(sku);
        return res>0;
    }
//商品搜索
    @Override
    public PageResult selectList(Integer pageIndex, Integer pageSize, String skuName) {

        PageHelper.startPage(pageIndex,pageSize);

        Page<PageQueryResponse> list = skuMapper.selectList(skuName);

        return new PageResult(pageIndex, pageSize, (long)list.getPages(), list.getTotal(), list.getResult());

    }

    @Override
    public Boolean updateSku(Long skuId ,SkuDto skuDto) {
        Sku sku = new Sku();
        BeanUtils.copyProperties(skuDto,sku);
        sku.setUpdateTime(LocalDateTime.now());
        sku.setSkuId(skuId);
        int res = skuMapper.updateSku(sku);
        return res>0;
    }
}
